package com.hrm.system.controller;

import com.hrm.common.controller.BaseController;
import com.hrm.common.entity.PageResult;
import com.hrm.common.entity.Result;
import com.hrm.common.entity.ResultCode;
import com.hrm.domain.system.Role;
import com.hrm.system.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping(value = "/sys") //sys/role
public class RoleController extends BaseController {

    @Autowired
    private RoleService roleService;


    /**
     * 保存角色
     */
    @RequestMapping(value = "/role", method = RequestMethod.POST)
    public Result addRole(@RequestBody Role Role) {
        Role.setCompanyId(companyId);
        roleService.addRole(Role);
        //响应结果
        return new Result(ResultCode.SUCCESS);
    }

    /**
     * 更新角色
     */
    @RequestMapping(value = "/role/{id}", method = RequestMethod.PUT)
    public Result updateRole(@PathVariable(value = "id") String id, @RequestBody Role Role) {
        Role.setId(id);
        roleService.updateRole(Role);
        return new Result(ResultCode.SUCCESS);
    }

    /**
     * id查找角色
     */
    @RequestMapping(value = "/role/{id}", method = RequestMethod.GET)
    public Result findCompanyById(@PathVariable(value = "id") String id) {
        Role Role = roleService.findRoleById(id);
        return new Result(ResultCode.SUCCESS, Role);
    }

    /**
     * 查找角色列表
     * 返回数据分页
     */
    @RequestMapping(value = "/role", method = RequestMethod.GET)
    public Result findRoles(Integer page, Integer size) {
        Page<Role> rolePage = roleService.findRoles(companyId, page, size);
        return new Result(ResultCode.SUCCESS, new PageResult<>(rolePage.getTotalElements(), rolePage.getContent()));
    }

    /**
     * id删除角色
     */
    @RequestMapping(value = "/role/{id}", method = RequestMethod.DELETE)
    public Result deleteCompany(@PathVariable(value = "id") String id) {
        roleService.deleteRole(id);
        return new Result(ResultCode.SUCCESS);
    }

    /**
     * 分配权限
     * put请求roleid和permission的map集合
     */
    @RequestMapping(value = "/role/asignPerms", method = RequestMethod.PUT)
    public Result asignRoles(@RequestBody Map<String, Object> map) {
        //获取userid 和 roleid集合
        String roleId = (String) map.get("id");
        List<String> permIds = (List<String>) map.get("permId");
        //调用asignRoles方法
        roleService.asignPerms(roleId, permIds);
        return new Result(ResultCode.SUCCESS);
    }
}
